<template>
  <div class="page-settings-panel-wrapper" v-if="showPanel">
    <div class="page-settings-panel-mask" @click="close"></div>
    <div class="page-settings-panel" :class="{ 'open': isOpen }">
      <div class="page-settings-panel-header">
        <h3>{{ props.title || '页面设置' }}</h3>
        <button class="close-btn" @click="close"></button>
      </div>
      <div class="page-settings-panel-content">
        <div class="settings-container">
          <!-- 基本配置 -->
          <div class="setting-section">
            <h4>基本配置</h4>
            <div class="setting-row">
              <label>编辑器模式</label>
              <select class="mode-select" v-model="formData.mode">
                <option :value="EditorMode.EDIT">编辑模式</option>
                <option :value="EditorMode.CLEAN">清洁模式</option>
                <option :value="EditorMode.READONLY">只读模式</option>
                <option :value="EditorMode.FORM">表单模式</option>
                <option :value="EditorMode.PRINT">打印模式</option>
                <option :value="EditorMode.DESIGN">设计模式</option>
              </select>
            </div>
            <div class="setting-row">
              <label>语言</label>
              <select class="locale-select" v-model="formData.locale">
                <option value="zh-CN">简体中文</option>
                <option value="en-US">English</option>
              </select>
            </div>
            <div class="setting-row">
              <label>页面宽度</label>
              <div class="size-control">
                <button class="size-btn" @click="decreaseWidth">-</button>
                <input type="number" class="size-input" v-model.number="formData.width" min="1">
                <button class="size-btn" @click="increaseWidth">+</button>
              </div>
            </div>
            <div class="setting-row">
              <label>页面高度</label>
              <div class="size-control">
                <button class="size-btn" @click="decreaseHeight">-</button>
                <input type="number" class="size-input" v-model.number="formData.height" min="1">
                <button class="size-btn" @click="increaseHeight">+</button>
              </div>
            </div>
            <div class="setting-row">
              <label>缩放比例</label>
              <input type="number" class="scale-input" v-model.number="formData.scale" min="0.1" max="5" step="0.1">
            </div>
            <div class="setting-row">
              <label>页面间距</label>
              <input type="number" class="scale-input" v-model.number="formData.pageGap" min="0" max="100" step="5">
            </div>
            <div class="setting-row">
              <label>页面模式</label>
              <select class="mode-select" v-model="formData.pageMode">
                <option :value="PageMode.PAGING">分页模式</option>
                <option :value="PageMode.CONTINUITY">连续模式</option>
              </select>
            </div>
            <div class="setting-row">
              <label>纸张方向</label>
              <select class="mode-select" v-model="formData.paperDirection">
                <option :value="PaperDirection.VERTICAL">垂直</option>
                <option :value="PaperDirection.HORIZONTAL">水平</option>
              </select>
            </div>
            <div class="setting-row">
              <label>渲染模式</label>
              <select class="mode-select" v-model="formData.renderMode">
                <option :value="RenderMode.SPEED">速度优先</option>
                <option :value="RenderMode.COMPATIBILITY">兼容优先</option>
              </select>
            </div>
            <div class="setting-row">
              <label>换行方式</label>
              <select class="mode-select" v-model="formData.wordBreak">
                <option :value="WordBreak.BREAK_WORD">单词换行</option>
                <option :value="WordBreak.BREAK_ALL">强制换行</option>
              </select>
            </div>
          </div>

          <!-- 样式配置 -->
          <div class="setting-section">
            <h4>样式配置</h4>
            <div class="setting-row">
              <label>默认字体</label>
              <input type="text" class="text-input" v-model="formData.defaultFont">
            </div>
            <div class="setting-row">
              <label>默认字号</label>
              <input type="number" class="scale-input" v-model.number="formData.defaultSize" min="1" max="100">
            </div>
            <div class="setting-row">
              <label>默认颜色</label>
              <input type="color" class="color-input" v-model="formData.defaultColor">
            </div>
            <div class="setting-row">
              <label>最小字号</label>
              <input type="number" class="scale-input" v-model.number="formData.minSize" min="1" max="100">
            </div>
            <div class="setting-row">
              <label>最大字号</label>
              <input type="number" class="scale-input" v-model.number="formData.maxSize" min="1" max="200">
            </div>
            <div class="setting-row">
              <label>下划线颜色</label>
              <input type="color" class="color-input" v-model="formData.underlineColor">
            </div>
            <div class="setting-row">
              <label>删除线颜色</label>
              <input type="color" class="color-input" v-model="formData.strikeoutColor">
            </div>
            <div class="setting-row">
              <label>超链接颜色</label>
              <input type="color" class="color-input" v-model="formData.defaultHyperlinkColor">
            </div>
          </div>

          <!-- 行配置 -->
          <div class="setting-section">
            <h4>行配置</h4>
            <div class="setting-row">
              <label>默认类型</label>
              <select class="mode-select" v-model="formData.defaultType">
                <option value="TEXT">文本</option>
                <option value="HEADING1">标题1</option>
                <option value="HEADING2">标题2</option>
                <option value="HEADING3">标题3</option>
                <option value="HEADING4">标题4</option>
                <option value="HEADING5">标题5</option>
                <option value="HEADING6">标题6</option>
                <option value="LIST">列表</option>
                <option value="IMAGE">图片</option>
              </select>
            </div>
            <div class="setting-row">
              <label>默认行边距</label>
              <input type="number" class="scale-input" v-model.number="formData.defaultRowMargin" min="0" max="10">
            </div>
            <div class="setting-row">
              <label>基本行边距高度</label>
              <input type="number" class="scale-input" v-model.number="formData.defaultBasicRowMarginHeight" min="1"
                max="50">
            </div>
            <div class="setting-row">
              <label>默认制表符宽度</label>
              <input type="number" class="scale-input" v-model.number="formData.defaultTabWidth" min="1" max="100">
            </div>
          </div>

          <!-- 界面配置 -->
          <div class="setting-section">
            <h4>界面配置</h4>
            <div class="setting-row">
              <label>页面边距</label>
              <div class="margin-inputs">
                <input type="number" v-model.number="marginTop" placeholder="上">
                <input type="number" v-model.number="marginRight" placeholder="右">
                <input type="number" v-model.number="marginBottom" placeholder="下">
                <input type="number" v-model.number="marginLeft" placeholder="左">
              </div>
            </div>
            <div class="setting-row">
              <label>遮罩边距</label>
              <div class="margin-inputs">
                <input type="number" v-model.number="maskMarginTop" placeholder="上">
                <input type="number" v-model.number="maskMarginRight" placeholder="右">
                <input type="number" v-model.number="maskMarginBottom" placeholder="下">
                <input type="number" v-model.number="maskMarginLeft" placeholder="左">
              </div>
            </div>
          </div>

          <!-- 背景配置 -->
          <div class="setting-section">
            <h4>背景配置</h4>
            <div class="setting-row">
              <label>背景颜色</label>
              <input type="color" class="color-input" v-model="backgroundColor">
            </div>
            <div class="setting-row">
              <label>背景图片</label>
              <input type="text" class="text-input" v-model="backgroundImage" placeholder="图片URL">
            </div>
            <div class="setting-row">
              <label>背景尺寸</label>
              <select class="mode-select" v-model="backgroundSize">
                <option :value="BackgroundSize.COVER">覆盖</option>
                <option :value="BackgroundSize.CONTAIN">包含</option>
              </select>
            </div>
            <div class="setting-row">
              <label>背景重复</label>
              <select class="mode-select" v-model="backgroundRepeat">
                <option :value="BackgroundRepeat.NO_REPEAT">不重复</option>
                <option :value="BackgroundRepeat.REPEAT">重复</option>
                <option :value="BackgroundRepeat.REPEAT_X">水平重复</option>
                <option :value="BackgroundRepeat.REPEAT_Y">垂直重复</option>
              </select>
            </div>
          </div>

          <!-- 预览区域 -->
          <div class="setting-section">
            <h4>预览</h4>
            <div class="preview-container">
              <div class="preview-canvas" :style="previewStyle"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="page-settings-panel-footer">
        <button class="btn-reset" @click="reset">重置</button>
        <div class="footer-buttons">
          <button class="cancel-btn" @click="close">取消</button>
          <button class="confirm-btn" @click="onConfirm">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { EditorMode, PageMode, PaperDirection, RenderMode, WordBreak } from '../../editor/dataset/enum/Editor';
import { BackgroundSize, BackgroundRepeat } from '../../editor/dataset/enum/Background';
import type { IEditorOption } from '../../editor/interface/Editor';
import type { IMargin } from '../../editor/interface/Margin';

/**
 * 页面设置面板选项接口
 */
interface IPageSettingsPanelOptions {
  title: string;
  data: IEditorOption;
  onConfirm?: (data: Partial<IEditorOption>) => void;
  onClose?: () => void;
}

// 组件属性
const props = defineProps<IPageSettingsPanelOptions>();

// 面板显示状态 - 从右侧滑出动画需要先隐藏再显示
const showPanel = ref(true);
const isOpen = ref(false); // 初始为false，在mounted后设置为true触发动画

/**
 * 表单数据对象，包含所有编辑器配置选项
 */
const formData = reactive<Partial<IEditorOption>>({
  margins: [100, 120, 100, 120] as IMargin,
  maskMargin: [60, 0, 30, 0] as IMargin,
  background: {
    color: '#FFFFFF',
    image: '',
    size: BackgroundSize.COVER,
    repeat: BackgroundRepeat.NO_REPEAT,
    applyPageNumbers: []
  }
});

// 边距相关的计算属性
const marginTop = computed({
  get: () => formData.margins?.[0] || 100,
  set: (value) => {
    if (!formData.margins) formData.margins = [100, 120, 100, 120] as IMargin;
    formData.margins[0] = value;
  }
});

const marginRight = computed({
  get: () => formData.margins?.[1] || 120,
  set: (value) => {
    if (!formData.margins) formData.margins = [100, 120, 100, 120] as IMargin;
    formData.margins[1] = value;
  }
});

const marginBottom = computed({
  get: () => formData.margins?.[2] || 100,
  set: (value) => {
    if (!formData.margins) formData.margins = [100, 120, 100, 120] as IMargin;
    formData.margins[2] = value;
  }
});

const marginLeft = computed({
  get: () => formData.margins?.[3] || 120,
  set: (value) => {
    if (!formData.margins) formData.margins = [100, 120, 100, 120] as IMargin;
    formData.margins[3] = value;
  }
});

// 遮罩边距相关的计算属性
const maskMarginTop = computed({
  get: () => formData.maskMargin?.[0] || 60,
  set: (value) => {
    if (!formData.maskMargin) formData.maskMargin = [60, 0, 30, 0] as IMargin;
    formData.maskMargin[0] = value;
  }
});

const maskMarginRight = computed({
  get: () => formData.maskMargin?.[1] || 0,
  set: (value) => {
    if (!formData.maskMargin) formData.maskMargin = [60, 0, 30, 0] as IMargin;
    formData.maskMargin[1] = value;
  }
});

const maskMarginBottom = computed({
  get: () => formData.maskMargin?.[2] || 30,
  set: (value) => {
    if (!formData.maskMargin) formData.maskMargin = [60, 0, 30, 0] as IMargin;
    formData.maskMargin[2] = value;
  }
});

const maskMarginLeft = computed({
  get: () => formData.maskMargin?.[3] || 0,
  set: (value) => {
    if (!formData.maskMargin) formData.maskMargin = [60, 0, 30, 0] as IMargin;
    formData.maskMargin[3] = value;
  }
});

// 背景相关的计算属性
const backgroundColor = computed({
  get: () => formData.background?.color || '#FFFFFF',
  set: (value) => {
    if (!formData.background) formData.background = { color: '#FFFFFF', image: '', size: BackgroundSize.COVER, repeat: BackgroundRepeat.NO_REPEAT, applyPageNumbers: [] };
    formData.background.color = value;
  }
});

const backgroundImage = computed({
  get: () => formData.background?.image || '',
  set: (value) => {
    if (!formData.background) formData.background = { color: '#FFFFFF', image: '', size: BackgroundSize.COVER, repeat: BackgroundRepeat.NO_REPEAT, applyPageNumbers: [] };
    formData.background.image = value;
  }
});

const backgroundSize = computed({
  get: () => formData.background?.size || BackgroundSize.COVER,
  set: (value) => {
    if (!formData.background) formData.background = { color: '#FFFFFF', image: '', size: BackgroundSize.COVER, repeat: BackgroundRepeat.NO_REPEAT, applyPageNumbers: [] };
    formData.background.size = value;
  }
});

const backgroundRepeat = computed({
  get: () => formData.background?.repeat || BackgroundRepeat.NO_REPEAT,
  set: (value) => {
    if (!formData.background) formData.background = { color: '#FFFFFF', image: '', size: BackgroundSize.COVER, repeat: BackgroundRepeat.NO_REPEAT, applyPageNumbers: [] };
    formData.background.repeat = value;
  }
});

// 初始化所有配置项，避免可能的undefined访问问题
onMounted(() => {
  // 基本配置
  formData.mode = props.data.mode || EditorMode.EDIT;
  formData.locale = props.data.locale || 'zh-CN';
  formData.width = props.data.width || 794;
  formData.height = props.data.height || 1123;
  formData.scale = props.data.scale || 1;
  formData.pageGap = props.data.pageGap || 20;
  formData.pageMode = props.data.pageMode || PageMode.PAGING;
  formData.paperDirection = props.data.paperDirection || PaperDirection.VERTICAL;
  formData.renderMode = props.data.renderMode || RenderMode.SPEED;
  formData.wordBreak = props.data.wordBreak || WordBreak.BREAK_WORD;

  // 样式配置
  formData.defaultFont = props.data.defaultFont || 'Microsoft YaHei';
  formData.defaultSize = props.data.defaultSize || 16;
  formData.defaultColor = props.data.defaultColor || '#000000';
  formData.minSize = props.data.minSize || 5;
  formData.maxSize = props.data.maxSize || 72;
  formData.underlineColor = props.data.underlineColor || '#000000';
  formData.strikeoutColor = props.data.strikeoutColor || '#FF0000';
  formData.defaultHyperlinkColor = props.data.defaultHyperlinkColor || '#0000FF';

  // 行配置
  formData.defaultType = props.data.defaultType || 'TEXT';
  formData.defaultRowMargin = props.data.defaultRowMargin || 1;
  formData.defaultBasicRowMarginHeight = props.data.defaultBasicRowMarginHeight || 8;
  formData.defaultTabWidth = props.data.defaultTabWidth || 32;

  // 界面配置
  formData.margins = props.data.margins || [100, 120, 100, 120] as IMargin;
  formData.maskMargin = props.data.maskMargin || [60, 0, 30, 0] as IMargin;

  // 背景配置
  formData.background = props.data.background || {
    color: '#FFFFFF',
    image: '',
    size: BackgroundSize.COVER,
    repeat: BackgroundRepeat.NO_REPEAT,
    applyPageNumbers: []
  };

  // 延迟设置isOpen为true，触发从右侧滑出的动画效果
  setTimeout(() => {
    isOpen.value = true;
  }, 50);
});

/**
 * 预览样式计算属性
 */
const previewStyle = computed(() => {
  const maxPreviewHeight = 300;

  // 计算预览区域的宽度和高度，保持比例
  const width = formData.width || 794;
  const height = formData.height || 1123;
  const scale = formData.scale || 1;

  // 计算缩放比例，确保预览区域不超过最大高度
  const previewScale = Math.min(1, maxPreviewHeight / (height * scale));

  // 计算最终尺寸
  const previewWidth = width * scale * previewScale;
  const previewHeight = height * scale * previewScale;

  return {
    width: `${previewWidth}px`,
    height: `${previewHeight}px`,
    backgroundColor: formData.background?.color || '#FFFFFF',
    backgroundImage: formData.background?.image ? `url(${formData.background.image})` : 'none',
    backgroundSize: formData.background?.size || 'cover',
    backgroundRepeat: formData.background?.repeat || 'no-repeat',
    margin: '0 auto',
    border: '1px solid #E0E0E0'
  };
});

/**
 * 增加宽度函数
 */
const increaseWidth = (): void => {
  formData.width = (formData.width || 794) + 10;
};

/**
 * 减少宽度函数
 */
const decreaseWidth = (): void => {
  formData.width = Math.max(10, (formData.width || 794) - 10);
};

/**
 * 增加高度函数
 */
const increaseHeight = (): void => {
  formData.height = (formData.height || 1123) + 10;
};

/**
 * 减少高度函数
 */
const decreaseHeight = (): void => {
  formData.height = Math.max(10, (formData.height || 1123) - 10);
};

/**
 * 更新预览函数
 */
const updatePreview = (): void => {
  // 由于使用了计算属性，这里不需要额外的更新逻辑
};

/**
 * 重置函数
 */
const reset = (): void => {
  // 重置为默认值
  formData.mode = EditorMode.EDIT;
  formData.locale = 'zh-CN';
  formData.width = 794;
  formData.height = 1123;
  formData.scale = 1;
  formData.pageGap = 20;
  formData.pageMode = PageMode.PAGING;
  formData.paperDirection = PaperDirection.VERTICAL;
  formData.renderMode = RenderMode.SPEED;
  formData.wordBreak = WordBreak.BREAK_WORD;

  formData.defaultFont = 'Microsoft YaHei';
  formData.defaultSize = 16;
  formData.defaultColor = '#000000';
  formData.minSize = 5;
  formData.maxSize = 72;
  formData.underlineColor = '#000000';
  formData.strikeoutColor = '#FF0000';
  formData.defaultHyperlinkColor = '#0000FF';

  formData.defaultType = 'TEXT';
  formData.defaultRowMargin = 1;
  formData.defaultBasicRowMarginHeight = 8;
  formData.defaultTabWidth = 32;

  formData.margins = [100, 120, 100, 120] as IMargin;
  formData.maskMargin = [60, 0, 30, 0] as IMargin;

  formData.background = {
    color: '#FFFFFF',
    image: '',
    size: BackgroundSize.COVER,
    repeat: BackgroundRepeat.NO_REPEAT,
    applyPageNumbers: []
  };

  updatePreview();
};

/**
 * 确认按钮点击事件处理
 */
const onConfirm = (): void => {
  try {
    // 构建返回数据
    const result: Partial<IEditorOption> = {
      // 基本配置
      mode: formData.mode,
      locale: formData.locale,
      width: formData.width,
      height: formData.height,
      scale: formData.scale,
      pageGap: formData.pageGap,
      pageMode: formData.pageMode,
      paperDirection: formData.paperDirection,
      renderMode: formData.renderMode,
      wordBreak: formData.wordBreak,

      // 样式配置
      defaultFont: formData.defaultFont,
      defaultSize: formData.defaultSize,
      defaultColor: formData.defaultColor,
      minSize: formData.minSize,
      maxSize: formData.maxSize,
      underlineColor: formData.underlineColor,
      strikeoutColor: formData.strikeoutColor,
      defaultHyperlinkColor: formData.defaultHyperlinkColor,

      // 行配置
      defaultType: formData.defaultType,
      defaultRowMargin: formData.defaultRowMargin,
      defaultBasicRowMarginHeight: formData.defaultBasicRowMarginHeight,
      defaultTabWidth: formData.defaultTabWidth,

      // 界面配置
      margins: formData.margins,
      maskMargin: formData.maskMargin,

      // 背景配置
      background: formData.background
    };

    // 调用确认回调函数
    if (props.onConfirm) {
      props.onConfirm(result);
    }

    // 关闭面板
    close();
  } catch (error) {
    console.error('保存配置失败:', error);
    alert('保存配置失败，请检查输入的数据格式');
  }
};

/**
 * 关闭函数
 */
const close = (): void => {
  isOpen.value = false;
  setTimeout(() => {
    showPanel.value = false;
    if (props.onClose) {
      props.onClose();
    }
  }, 300);
};
</script>

<style scoped src="./page-settings-panel.css"></style>